#include "drawing_board.h"
#include <QImage>
#include <QPixmap>
#include <QColor>
#include <QDebug>

DrawBoard::DrawBoard(QWidget *parent):QLabel(parent)
{
    m_bMouseDown = false;
    m_startPoint = QPoint(0,0);
    m_endPoint = QPoint(0,0);


}

DrawBoard::~DrawBoard()
{

}

void DrawBoard::initWithImage(QString imgName)
{
    QImage qimg;
    qimg.load(imgName);
    m_qimg = qimg.scaled(QSize(800, 600),Qt::KeepAspectRatio);

//    m_showImage = QImage(m_qimg.size(), QImage::Format_RGB888);
    m_showPixmap = QPixmap::fromImage(m_qimg);
    this->setPixmap(m_showPixmap);
}

void DrawBoard::initWithColor(QColor color)
{

}

void DrawBoard::mouseMoveEvent(QMouseEvent *event)
{
    if(m_bMouseDown)
    {
        m_endPoint.setX(event->pos().x());
        m_endPoint.setY(event->pos().y());
        m_painter.begin(&m_showPixmap);
        m_painter.drawImage(0, 0, m_qimg);
        m_painter.setPen(QColor(255,0,0));

        QString output = QString("(%1, %2, %3, %4)").arg(m_startPoint.x()).arg(m_startPoint.y()).arg(m_endPoint.x()).arg(m_endPoint.y());
        m_painter.drawText(QRect(20, 20, 240, 80), output);

        m_painter.drawRect(QRect(m_startPoint, m_endPoint));
        m_painter.end();
        this->setPixmap(m_showPixmap);
    }
}

void DrawBoard::mousePressEvent(QMouseEvent *event)
{
    m_startPoint.setX(event->pos().x());
    m_startPoint.setY(event->pos().y());
    m_bMouseDown = true;

    qDebug() <<event->pos() <<endl;
}

void DrawBoard::mouseReleaseEvent(QMouseEvent *event)
{
    m_endPoint.setX(event->pos().x());
    m_endPoint.setY(event->pos().y());
    m_painter.begin(&m_showPixmap);
    m_painter.drawImage(0, 0, m_qimg);
    m_painter.setPen(QColor(255,0,0));

    QString output = QString("(%1, %2, %3, %4)").arg(m_startPoint.x()).arg(m_startPoint.y()).arg(m_endPoint.x()).arg(m_endPoint.y());
    m_painter.drawText(QRect(20, 20, 240, 80), output);

    m_painter.drawRect(QRect(m_startPoint, m_endPoint));
    m_painter.end();
    this->setPixmap(m_showPixmap);
    m_bMouseDown = false;
    qDebug() <<event->pos() <<endl;
}


